<script setup lang="ts">
  import { ref, h } from "vue";
  import { Filter } from "@/components/SideBar";
  import Dialog from "@/components/sql/Dialog.vue";
  import { ElCascader } from "element-plus";

  const fd: gt.components.SideBar.Filter[] = [
    // {
    //   value: "新增", type: "button", opt: { onClick() { click(0); }, type: "primary", class: "mac-ico-add-round", disabled: true }
    // },
  ],
    page = ref<gt.PageData<gt.sql.user>>({ current: 1, size: 10, total: 0, data: [] }),
    filterData = ref<any>(fd),
    tip = ref([
      { label: `查看`, value: 2, cls: "mac-ico-search", per: true },
      { label: `修改用户名`, value: 0, cls: "mac-ico-people-list", per: true },
      { label: "重设密码", value: 1, cls: "mac-ico-people-list-light", per: true },
      { label: `修改昵称`, value: 3, cls: "mac-ico-my", per: true },
      { label: `修改抽成`, value: 4, cls: "mac-ico-warning", per: api.s.distribution },
      { label: `转化为商家`, value: 5, cls: "mac-ico-home", per: api.s.distribution },
    ] as const),
    dig = ref<InstanceType<typeof Dialog>>()
    ;


  async function click(method: number, p: gt.sql.user) {
    let gid = p.gid;
    switch (method) {
      case 2:
        if (dig.value) {
          dig.value.open("user", method, p);
        }
        break;
      case 0: // 修改用户名
        ElMessageBox({
          title: tip.value[1].label,
          message: "请输入新的用户名(请确保唯一)",
          inputValue: p.username,
          inputPlaceholder: "请输入新的唯一用户名",
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: "用户名长度限制为5-20",
          showInput: true,
          callback() { },
          async beforeClose(action, instance, done) {
            if (action == "confirm") {
              if (await api.request({ id: p.id, username: instance.inputValue }, "userChange_username")) {
                p.username = instance.inputValue;
              } else { return; }
            }
            done();
          },
        });
        break;
      case 1: // 重设密码
        ElMessageBox({
          title: tip.value[2].label,
          message: "请输入新的登录密码",
          inputPlaceholder: "请输入密码",
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: "密码长度限制为5-20",
          showInput: true,
          callback() { },
          async beforeClose(action, instance, done) {
            if (action == "confirm" && !(await api.request({ id: p.id, password: instance.inputValue }, "userChange_password"))) {
              return;
            }
            done();
          },
        });
        break;
      case 3: // 修改昵称
        ElMessageBox({
          title: tip.value[3].label,
          message: "请输入新的昵称",
          inputPlaceholder: "请输入昵称",
          inputValue: p.name,
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: "昵称长度限制为5-20",
          showInput: true,
          callback() { },
          async beforeClose(action, instance, done) {
            if (action == "confirm") {
              if (await api.request({ id: p.id, name: instance.inputValue }, "userChange_name")) {
                p.name = instance.inputValue;
              } else {
                return;
              }
            }
            done();
          },
        });
        break;
      case 4: // 修改抽成百分比
        ElMessageBox({
          title: tip.value[4].label,
          message: "请输入新的抽成百分比%",
          inputPlaceholder: "请输入抽成百分比%",
          inputValue: p.commission.toString(),
          showInput: true,
          callback() { },
          async beforeClose(action, instance, done) {
            if (action == "confirm") {
              if (await api.request({ id: p.id, commission: instance.inputValue }, "userChange_commission")) {
                p.commission = parseInt(instance.inputValue);
              } else {
                return;
              }
            }
            done();
          },
        });
        break;
      case 5: // 转化为商家
        ElMessageBox({
          title: tip.value[5].label,
          message: h(ElCascader, {
            modelValue: gid,
            options: (await gd.groupTree).find(e => e.id == "1")?.children,
            props: {
              expandTrigger: "hover",
              checkStrictly: true,
              emitPath: false,
              value: "id",
              label: "name"
            }, clearable: true, collapseTagsTooltip: true, placeholder: "请选择所属商家",
            "onUpdate:modelValue"(v) { gid = v as string; }
          }),
          callback() { },
          async beforeClose(action, _, done) {
            if (action == "confirm" && gid && gid != "2") {
              if (await api.request({ id: p.id, gid, merch: true }, "userChange_gid")) {
                p.gid = gid;
                const i = page.value.data.findIndex(e => e.id == p.id);
                if (i >= 0) {
                  page.value.data.splice(i, 1);
                }
                page.value.total--;
              } else {
                return;
              }
            }
            done();
          },
        });
        break;

      default:
        break;
    }
  }
  async function init() {
    const qr: R<gt.sql.user>[] = [{ field: "gid", logic: "=", value: "2" }];

    const res = await gd.user.read({
      "#page": { current: page.value.current, size: page.value.size },
      "#rule": qr,
      "#order": [["createTime", "DESC"]]
    });
    page.value = res;
  }
  init();
</script>
<template>
  <LayoutPage>
    <div class="index whf oh y">
      <Filter :data="filterData" isRow class="mb1em" />
      <el-table stripe highlight-current-row :data="page.data" class="wf fg1" type="expand" row-key="id">
        <el-table-column prop="id" label="id" width="100" show-overflow-tooltip />
        <el-table-column prop="_createTime" label="创建时间" width="120" show-overflow-tooltip />
        <el-table-column prop="name" label="昵称" show-overflow-tooltip />
        <el-table-column prop="username" label="用户名" show-overflow-tooltip />
        <el-table-column prop="commission" label="提成(%)" width="80" show-overflow-tooltip />
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <div class="buttons x zb">
              <template v-for="a in tip">
                <el-tooltip v-if="a.per" :content="a.label">
                  <div :class="a.cls" @click.stop="click(a.value, row)" />
                </el-tooltip>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background layout="prev, pager, next, jumper, ->, sizes, total"
        :page-sizes="[10, 20, 30, 40, 50, 100]" v-model:page-size="page.size" :total="page.total"
        v-model:currentPage="page.current" @size-change="init" @current-change="init" />
      <Dialog ref="dig" />
    </div>
  </LayoutPage>
</template>
<style lang="scss" scoped>
  .index {
    position: relative;
    .buttons {
      >div {
        cursor: pointer;
        padding: 0 0.4em;
        font-weight: 600;
        &:hover {
          border: 1px solid #a5a5a5;
          box-sizing: border-box;
          border-radius: 0.5em;
          box-shadow: 0 0 10px #000;
        }
      }
      >.mac-ico-add-round, >.mac-ico-people-list {
        color: var(--color-success);
      }
      >.mac-ico-edit, >.mac-ico-warning {
        color: var(--color-warning);
      }
      >.mac-ico-search {
        color: var(--color-primary);
      }
      >.mac-ico-delete, >.mac-ico-my {
        color: var(--color-error);
      }
    }
    .el-table {

      .blueRow {
        color: blue;
      }
      .redRow {
        color: red;
      }
    }
  }
</style>